﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using FishServe.Core.Manifest;
using System.IO;

namespace FishServe.Core
{
    public class ModuleManifestResolver
    {
        private string _applicationDir;
        private ReleaseManifest _releaseManifest;
        private List<ReleaseManifest> _associatedReleaseManifests = new List<ReleaseManifest>();

        public ModuleManifestResolver(string applicationDir, ReleaseManifest releaseManifest)
        {
            _applicationDir = applicationDir;
            _releaseManifest = releaseManifest;
        }

        public ModuleManifest GetModuleManifest(Module module)
        {
            AssemblyName moduleAssemblyName = module.GetType().Assembly.GetName();

            foreach (ModuleManifest moduleManifest in _releaseManifest.ModuleManifests)
            {
                if (moduleManifest.Module.Name == moduleAssemblyName.Name &&
                    moduleManifest.Module.Version == moduleAssemblyName.Version)
                    return moduleManifest;
            }

            foreach( ReleaseManifest associatedReleaseManifest in _associatedReleaseManifests )
            {
                if (associatedReleaseManifest.Name == moduleAssemblyName.Name)
                {
                    foreach (ModuleManifest moduleManifest in associatedReleaseManifest.ModuleManifests)
                    {
                        if (moduleManifest.Module.Name == moduleAssemblyName.Name &&
                            moduleManifest.Module.Version == moduleAssemblyName.Version)
                            return moduleManifest;
                    }
                }
            }

            foreach (AssociatedReleaseManifestInfo associatedReleaseManifestInfo in _releaseManifest.AssociatedReleaseManifests)
            {
                if (associatedReleaseManifestInfo.Name == moduleAssemblyName.Name)
                {
                    string filename = String.Format("{0}.{1}.manifest", associatedReleaseManifestInfo.Name, associatedReleaseManifestInfo.Version);
                    ReleaseManifest releaseManifest = ReleaseManifestReader.Read(_applicationDir, filename);
                    _associatedReleaseManifests.Add(releaseManifest);

                    foreach (ModuleManifest moduleManifest in releaseManifest.ModuleManifests)
                    {
                        if (moduleManifest.Module.Name == moduleAssemblyName.Name &&
                            moduleManifest.Module.Version == moduleAssemblyName.Version)
                            return moduleManifest;
                    }
                }
            }

            return null;
        }
    }
}
